package com.solocredit.finance.ui.user.act

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.viewpager.widget.ViewPager
import com.solocredit.finance.R
import com.solocredit.finance.base.utils.ImageUtil
import com.solocredit.finance.base.utils.TitleBarUtil
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.databinding.ActMullaUserVipBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.MvpAct
import com.solocredit.finance.ui.user.impl.MullaUserVipPresenterImpl
import com.solocredit.finance.ui.user.view.IMullaUserVipView
import com.solocredit.finance.utils.dialog.UserBirthdayBenefitsDialog
import com.solocredit.finance.utils.dialog.UserGradeQADialog
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.MullaCustomDataHelper
import com.solocredit.finance.weight.banner.XBannerUtils
import com.solocredit.finance.weight.banner.entity.UserVipInfo
import com.solocredit.finance.weight.banner.transformers.Transformer

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/14 19:40
 * @Annotation：用户VIP等级中心
 */
class MullaUserVipAct: MvpAct<IMullaUserVipView, MullaUserVipPresenterImpl>(),IMullaUserVipView {
    lateinit var binding: ActMullaUserVipBinding

    /**
     * 生日福利领取状态
     * -1: 未设置生日
     * 0 ：待领取
     * 1 ：已领取
     * 2 ：不可领取
     */
    private var birthdayBenefitsReceiveStatus = -1

    companion object {
        private const val INTENT_KEY_INDEX = "showIndex"
        fun start(context: Context, index: Int) {
            val intent = Intent(context, MullaUserVipAct::class.java)
            intent.putExtra(INTENT_KEY_INDEX, index)
            context.startActivity(intent)
        }
    }

    override fun createPresenter(): MullaUserVipPresenterImpl {
        return MullaUserVipPresenterImpl(this)
    }

    override fun getMullaRootView(): View {
        binding = ActMullaUserVipBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        TitleBarUtil.setStatusBarLightMode(this, false)
        binding.parentLayout.setPadding(0, TitleBarUtil.getStatusBarHeight(),0,0)
        initMullaGradeBanner()

        binding.ivLanguage.visibility = View.GONE
        if (MullaConfigs.isTanz()){
            binding.ivLanguage.visibility = View.VISIBLE
        }
    }

    override fun initMullaListener() {
        //返回
        binding.imgBack.setOnClickListener {
            finish()
        }
        //客服
        binding.imgKefu.setOnClickListener {
            showMullaKefuDialog("Grade Center Page")
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,"Grade Center Page")
        }
        //语言切换
        binding.ivLanguage.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LANGUAGE,"Grade Center Page")
            showMullaLanguageDialog("Grade Center Page", onSelectCallback = {
            })
        }

        //生日福利
        binding.birthdayLayout.setOnClickListener {
            when(birthdayBenefitsReceiveStatus){
                -1 -> {
                    //未设置生日 - 跳转到个人简介
                    onIntent(MullaUserProfileAct::class.java)
                }
                0 -> {
                    showMullaLoading(isTOuchOut = false, isCancel = true)
                    presenter.saveMullaUserBirthdayBenefitsReceiveTimeAction()
                }
            }
        }
    }

    override fun initMullaData() {
        presenter.loadMullaVipGradeListAction()
        presenter.loadMullaUserBirthdayBenefitsStatus()

        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.visibility = View.VISIBLE

            ImageUtil.instance?.loadImageUrl(this,binding.imgLicenseLogo, licenseInfo.optString("logo"))
            binding.textLicenseDesc.text = licenseInfo.optString("desc")
            binding.textLicenseValue.text = licenseInfo.optString("companyName")
        }
    }

    /* 初始化banner */
    private fun initMullaGradeBanner() {
        // 设置XBanner的页面切换特效
        binding.xBanner.setPageTransformer(Transformer.Scale)
        // 设置XBanner页面切换的时间，即动画时长
        binding.xBanner.setPageChangeDuration(1000)
        binding.xBanner.setAutoPlayTime(3000)
        binding.xBanner.setSlideScrollMode(1)
        //设置是否允许用户手指滑动
        binding.xBanner.setAllowUserScrollable(true)
        //是否自动轮播
        binding.xBanner.setAutoPlayAble(false)
        //设置非自动轮播状态下是否可以循环切换
        binding.xBanner.setHandLoop(false)
        //显示指示器
        binding.xBanner.setPointsIsVisible(false)
        binding.xBanner.setShowIndicatorOnlyOne(false)
        //是否开启一屏多个模式
        binding.xBanner.setIsClipChildrenMode(true)
        //修改一屏多显模式左右间距
        binding.xBanner.setClipChildrenLeftRightMargin(XBannerUtils.dp2px(this, 20f), XBannerUtils.dp2px(this, 20f))

        //加载广告图片
        binding.xBanner.loadImage { banner, model, view, position ->
            //2、返回的图片路径为Object类型，你只需要强转成你传输的类型就行，切记不要胡乱强转！
            val item = model as UserVipInfo

            val itemLayout = view.findViewById<RelativeLayout>(R.id.itemLayout)
            itemLayout.setBackgroundResource(item.bannerResId)

            val imgMore = view.findViewById<ImageView>(R.id.imgMore)
            imgMore.setImageResource(item.moreIcon)

            val imgVipText = view.findViewById<ImageView>(R.id.imgVipText)
            imgVipText.setImageResource(item.vipText)

            val imgDoubt = view.findViewById<ImageView>(R.id.imgDoubt)
            imgDoubt.setImageResource(item.vipDoubt)

            val imgLable = view.findViewById<ImageView>(R.id.imgLable)
            imgLable.setImageResource(item.vipLable)

            val textNickName = view.findViewById<TextView>(R.id.textNickName)
            textNickName.setTextColor(item.colorId)
            textNickName.text = MullaCustomDataHelper.getMullaCustomUserName()

            val imgAvatar = view.findViewById<ImageView>(R.id.imgAvatar)
            imgAvatar.setImageResource(MullaCustomDataHelper.getMullaCustomUserAvatar())
        }
        binding.xBanner.setOnItemClickListener { banner, model, view, position ->
            val item = model as UserVipInfo
            //个人简介
            val profileLayout = view.findViewById<LinearLayout>(R.id.profileLayout)
            profileLayout.setOnClickListener {
                onIntent(MullaUserProfileAct::class.java)
            }
            //等级问答
            val qaLayout = view.findViewById<LinearLayout>(R.id.qaLayout)
            qaLayout.setOnClickListener {
                val qaDialog = UserGradeQADialog(this)
                qaDialog.show()
            }
        }
        binding.xBanner.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }
            override fun onPageSelected(position: Int) {
                showMullaGradeBackgroundResource(position)
            }
            override fun onPageScrollStateChanged(state: Int) {
            }
        })
    }

    /**
     * 获取查看的产品名称
     */
    private fun showDefaultIndex(): Int {
        var showIndex = getMullaUserVip() - 1
        intent.extras?.let {
            showIndex = it.getInt(INTENT_KEY_INDEX,0)
        }
        return showIndex
    }

    /**
     * 设置等级banner
     */
    override fun showMullaVipGradeList(gradeList: ArrayList<UserVipInfo>) {
        binding.xBanner.setBannerData(R.layout.item_mulla_vip_grade,gradeList)

        val curtIndex = showDefaultIndex()
        //当前VIP等级为1,不会触发onPageSelected 回调， 需要手动设置背景
        if (curtIndex == 0){
            showMullaGradeBackgroundResource(0)
        } else {
            binding.xBanner.bannerCurrentItem = curtIndex
        }
    }

    /**
     * 设置背景
     */
    private fun showMullaGradeBackgroundResource(position: Int){
        presenter.vipGradeList?.let {
            val item = it[position]
            binding.parentLayout.setBackgroundResource(item.backgroundResId)
            binding.textVipBenefits.text = String.format(getString(R.string.vip_benefits),item.vGrade)

            if (getMullaUserVip() < item.vip){//显示等级未达到
                binding.unableLayout.visibility = View.VISIBLE
            } else {
                binding.unableLayout.visibility = View.INVISIBLE
            }
            showMullaGradeBenefitsView(item)
        }
    }

    /**
     * 显示等级权益
     */
    private fun showMullaGradeBenefitsView(item: UserVipInfo){
        val benefitsObj = item.vipBenefits
        binding.imgDiscount.setImageResource(benefitsObj.optInt("discountIcon"))
        if (benefitsObj.optBoolean("discountUnlock")){
            binding.imgDiscountUnlock.visibility = View.VISIBLE
        } else {
            binding.imgDiscountUnlock.visibility = View.GONE
        }
        binding.textDiscountTitle.setTextColor(benefitsObj.optInt("titleColor"))
        when(item.vip){
            2 -> {
                //优惠券兑换折扣
                val customData = MullaCustomConfigsHelper.getMullaCustomData()
                val couponRateVip = customData?.optJSONArray("couponRateVip")
                couponRateVip?.let {
                    val couponRateVip2 = it.optDouble(1,1.0)
                    val showRate = (100 - (couponRateVip2 * 100)).toInt()
                    binding.textDiscountDesc.text = String.format(getString(benefitsObj.optInt("discountDes")),"$showRate%")
                }
                binding.textRepaymentDesc.text = String.format(getString(benefitsObj.optInt("repaymentDes")),"1.5")
                binding.textRepaymentDesc.setTextColor(Color.parseColor("#FFFF7121"))

            }
            3 -> {
                //优惠券兑换折扣
                val customData = MullaCustomConfigsHelper.getMullaCustomData()
                val couponRateVip = customData?.optJSONArray("couponRateVip")
                couponRateVip?.let {
                    val couponRateVip3 = it.optDouble(2,1.0)
                    val showRate = (100 - (couponRateVip3 * 100)).toInt()
                    binding.textDiscountDesc.text = String.format(getString(benefitsObj.optInt("discountDes")),"$showRate%")
                }
                binding.textRepaymentDesc.text = String.format(getString(benefitsObj.optInt("repaymentDes")),"2")
                binding.textRepaymentDesc.setTextColor(Color.parseColor("#FFFF7121"))
            }
            else -> {
                binding.textDiscountDesc.text = getString(benefitsObj.optInt("discountDes"))
                binding.textRepaymentDesc.text = getString(benefitsObj.optInt("repaymentDes"))
                binding.textRepaymentDesc.setTextColor(benefitsObj.optInt("desColor"))
            }
        }
        binding.textDiscountDesc.setTextColor(benefitsObj.optInt("desColor"))

        binding.imgRepayment.setImageResource(benefitsObj.optInt("repaymentIcon"))
        if (benefitsObj.optBoolean("repaymentUnlock")){
            binding.imgRepaymentUnlock.visibility = View.VISIBLE
        } else {
            binding.imgRepaymentUnlock.visibility = View.GONE
        }
        binding.textRepaymentTitle.setTextColor(benefitsObj.optInt("titleColor"))

        binding.imgBirthday.setImageResource(benefitsObj.optInt("birthdayIcon"))
        binding.textBirthdayTitle.setTextColor(benefitsObj.optInt("titleColor"))

        binding.imgOther.setImageResource(benefitsObj.optInt("otherIcon"))
        binding.textOtherTitle.setTextColor(benefitsObj.optInt("titleColor"))
        binding.textOtherDesc.text = getString(benefitsObj.optInt("otherDes"))
        binding.textOtherDesc.setTextColor(benefitsObj.optInt("desColor"))
    }

    /**
     * 设置生日福利状态 status
     * -1: 未设置生日
     * 0 ：待领取
     * 1 ：已领取
     * 2 ：不可领取
     */
    override fun showMullaUserBirthdayBenefitsView(status: Int){
        birthdayBenefitsReceiveStatus = status
        when(status){
            -1 -> {
                //未设置生日 - 点击跳转到 “个人简介” 页面
                binding.textBirthdayDesc.text = getString(R.string.vip_birthday_not_set)
                binding.textBirthdayDesc.setTextColor(Color.parseColor("#FF9599BA"))
                binding.birthdayLayout.isEnabled = true
            }
            0 -> {
                //待领取 - 点击领取
                binding.textBirthdayDesc.text = getString(R.string.vip_birthday_receive_wait)
                binding.textBirthdayDesc.setTextColor(Color.parseColor("#FFFFC971"))
                binding.birthdayLayout.isEnabled = true
            }
            1 -> {
                //已领取 - 不可点击
                binding.textBirthdayDesc.text = getString(R.string.vip_birthday_received)
                binding.textBirthdayDesc.setTextColor(Color.parseColor("#FF8CFF98"))
                binding.birthdayLayout.isEnabled = false
            }
            else -> {
                //不可领取- 不可点击
                binding.textBirthdayDesc.text = getString(R.string.vip_birthday_tips)
                binding.textBirthdayDesc.setTextColor(Color.parseColor("#FF9599BA"))
                binding.birthdayLayout.isEnabled = false
            }
        }
    }

    /**
     * 生日福利领取成功
     */
    override fun showMullaUserBirthdayBenefitsReceiveSuccess(points: String) {
        val birthdayDialog = UserBirthdayBenefitsDialog(this)
        birthdayDialog.setCancelable(true)
        birthdayDialog.setCanceledOnTouchOutside(false)
        birthdayDialog.show()
        birthdayDialog.showMullaUserBirthdayPoints(points)
    }

    override fun onMullaEvent(event: MullaEventData) {
        //刷新自定义数据成功
        if (event.eventType == MullaEventData.TYPE.MULLA_CUSTOM_DATA_REFRESHED){
            presenter.loadMullaVipGradeListAction()
            presenter.loadMullaUserBirthdayBenefitsStatus()
        }
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_GRADE_CENTER_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_GRADE_CENTER_END)
    }
}